<template>
  <div>
    <box t1="商品管理" t2="分类参数">
      <el-row>
        <el-col>
          <el-alert :closable="false" show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
        </el-col>
      </el-row>
      <br>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择器的v-model指向的必须是一个array -->
          <el-cascader
            v-model="selectedCateKeys"
            @change="changeSelected"
            :options="catesList"
            :props="cateProp"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border="" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="closeHandle(index,scope.row)"
                >{{ item }}</el-tag>
                <!-- 输入框切换按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加参数的按钮 -->
          <el-button
            @click="showAddDialog"
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
          >添加属性</el-button>
          <el-table :data="onlyTableData" border="" stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="closeHandle(index,scope.row)"
                >{{ item }}</el-tag>
                <!-- 输入框切换按钮 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  @click="deleteParams(scope.row.attr_id)"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </box>
    <!-- 新增参数弹窗 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="$refs.addFormRef.resetFields()"
    >
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules">
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数弹窗 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="$refs.editFormRef.resetFields()"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item prop="attr_name" :label="titleText">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catesList: [],
      selectedCateKeys: [],
      cateProp: {
        // 表示触发下一级菜单的方式
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      addForm: {
        attr_name: ""
      },
      addDialogVisible: false,
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      },
      editForm: {
        attr_name: ""
      },
      editDialogVisible: false,
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCatesList();
  },
  methods: {
    async getCatesList() {
      const { data: res } = await this.$http.get("categories");
      // 这个接口 数据在 data的result属性上
      this.catesList = res.data;
    },
    // 改变级联选择框值的时候触发
    changeSelected() {
      if (this.selectedCateKeys.length < 3) {
        console.log(11);
        return (this.selectedCateKeys = []);
      }
      this.getParamsList();
    },
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsList();
    },
    // 获取分类下的参数列表
    async getParamsList() {
      // 因为我们会在点击tab页切换也调用该获取参数的函数
      // 如果不加此判断 可能出来没有选择分类 而直接点击切换tab页的情况
      if (this.selectedCateKeys.length < 3) {
        return this.$message.error("请先选择分类");
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );

      // 为了方便展示参数可选项 我们要把attr_vals转化为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.split(" ");
        // 为了方便控制每一行的展开行中的按钮/输入框切换
        item.inputVisible = false;
        item.inputValue = "";
      });

      if (this.activeName === "many") {
        this.manyTableData = res.data;
        console.log(this.manyTableData);
      } else {
        this.onlyTableData = res.data;
        console.log(this.onlyTableData);
      }
    },
    showAddDialog() {
      this.addDialogVisible = true;
    },
    //展示编辑弹窗
    async showEditDialog(id) {
      //根据id获取最新的参数对象
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { attr_sel: this.activeName } }
      );
      if (res.meta.status !== 200) {
        return;
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    //添加参数函数 categories/:id/attributes
    async addParams() {
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
      );
      if (res.meta.status !== 201) {
        return this.$message.error("添加参数失败");
      }
      //成功关闭弹窗 重新加载列表数据
      this.addDialogVisible = false;
      this.getParamsList();
    },
    // 编辑参数函数
    async editParams() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.editForm.attr_vals
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改失败");
      }
      this.editDialogVisible = false;
      this.getParamsList();
    },
    // 删除参数的函数
    async deleteParams(id) {
      // 调用confirm弹窗
      let result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (result != "confirm") {
        return this.$message.info("用户取消删除");
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      // 成功后 重新加载列表数据
      this.getParamsList();
    },
    // 输入框 转化 为 按钮
    handleInputConfirm(row) {
      row.inputVisible = false;

      // 完成添加参数可选项
      if (!row.inputValue) {
        // 如果用户没有输入内容 终止函数执行
        return;
      }
      row.attr_vals.push(row.inputValue);
      // 为了防止keyup触发该函数两次
      row.inputValue = "";
      this.saveAttrVals(row);
    },
    // 按钮转化为 输入框
    showInput(row) {
      row.inputVisible = true;
      // 我们要让输入框获得焦点
      // 说明我们要操作dom元素 input
      // 如何才能获得input元素呢？
      //  this.$refs.saveTagInput 得到el-input 组件对象
      // 用el-input组件对象 .$refs.input 得到input元素
      // 如果直接向下面这样使用 会报错 找不到这个输入框组件
      // 原因是因为 row.inputVisible = true 改完数据之后 页面重绘是需要时间，但是代码执行肯定是在页面重绘之前 所以获取不到页面上的组件
      // 解决方案就是等页面重绘完 再去设置获取焦点
      // this.$refs.saveTagInput.$refs.input.focus()
      // $nextTick可以理解为数据改变之后 页面也改变了 才会去调用它的回调函数
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除参数可选项的事件函数
    closeHandle(index, row) {
      row.attr_vals.splice(index, 1);
      this.saveAttrVals(row);
    },
    // 修改参数可选项的请求函数
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("操作失败");
      }
      this.$message.success("操作成功");
    }
  },
  computed: {
    isBtnDisabled: function() {
      if (this.selectedCateKeys.length < 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId: function() {
      return this.selectedCateKeys[this.selectedCateKeys.length - 1];
    },
    titleText: function() {
      if (this.activeName == "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-cascader {
  width: 20%;
  margin-left: 8px;
}
.el-tag {
  margin-right: 20px;
}
.input-new-tag {
  width: 120px;
}
</style>